import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Modal, Form, Input, InputNumber, Switch, message, Popconfirm, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, CheckCircleOutlined } from '@ant-design/icons';
import api from '../services/api';

const { TextArea } = Input;

const AIModelPage = () => {
  const [loading, setLoading] = useState(false);
  const [models, setModels] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingModel, setEditingModel] = useState(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchModels();
  }, []);

  const fetchModels = async () => {
    try {
      setLoading(true);
      const response = await api.getAIModels();
      if (response.success) {
        setModels(response.data);
      }
    } catch (error) {
      // 错误已在 request.js 中处理
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingModel(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingModel(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      if (editingModel) {
        // 更新
        await api.updateAIModel(editingModel.id, values);
        message.success('模型配置更新成功');
      } else {
        // 创建
        await api.createAIModel(values);
        message.success('模型配置创建成功');
      }

      setModalVisible(false);
      fetchModels();
    } catch (error) {
      // 错误已在 request.js 中处理
    } finally {
      setLoading(false);
    }
  };

  const handleActivate = async (id) => {
    try {
      setLoading(true);
      await api.activateAIModel(id);
      message.success('模型已激活');
      fetchModels();
    } catch (error) {
      // 错误已在 request.js 中处理
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id) => {
    try {
      setLoading(true);
      await api.deleteAIModel(id);
      message.success('模型配置已删除');
      fetchModels();
    } catch (error) {
      // 错误已在 request.js 中处理
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 80,
      render: (isActive) => (
        isActive ? (
          <Tag color="success" icon={<CheckCircleOutlined />}>激活</Tag>
        ) : (
          <Tag>未激活</Tag>
        )
      )
    },
    {
      title: '显示名称',
      dataIndex: 'display_name',
      key: 'display_name',
      width: 150
    },
    {
      title: '模型标识',
      dataIndex: 'model_name',
      key: 'model_name',
      width: 150
    },
    {
      title: 'API 地址',
      dataIndex: 'base_url',
      key: 'base_url',
      ellipsis: true
    },
    {
      title: 'API Key',
      dataIndex: 'api_key',
      key: 'api_key',
      width: 150,
      render: (key) => key ? `${key.substring(0, 10)}...` : '-'
    },
    {
      title: 'Max Tokens',
      dataIndex: 'max_tokens',
      key: 'max_tokens',
      width: 100
    },
    {
      title: '温度',
      dataIndex: 'temperature',
      key: 'temperature',
      width: 80
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <div style={{ display: 'flex', gap: '8px' }}>
          {!record.is_active && (
            <Button
              type="primary"
              size="small"
              onClick={() => handleActivate(record.id)}
            >
              激活
            </Button>
          )}
          <Button
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          {!record.is_active && (
            <Popconfirm
              title="确定要删除这个模型配置吗？"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                size="small"
                danger
                icon={<DeleteOutlined />}
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </div>
      )
    }
  ];

  return (
    <Card
      title="AI 模型配置"
      extra={
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          添加模型
        </Button>
      }
    >
      <div style={{ marginBottom: 16, padding: '12px', background: '#fff7e6', border: '1px solid #ffd591', borderRadius: '4px' }}>
        <strong>💡 提示：</strong>
        <ul style={{ marginBottom: 0, paddingLeft: 20 }}>
          <li>只能有一个模型处于激活状态</li>
          <li>激活的模型将用于生成学生分析报告</li>
          <li>支持 OpenAI、DeepSeek、Ollama 等兼容 OpenAI API 的模型</li>
          <li>API Key 将加密存储，请妥善保管</li>
        </ul>
      </div>

      <Table
        columns={columns}
        dataSource={models}
        rowKey="id"
        loading={loading}
        pagination={false}
      />

      <Modal
        title={editingModel ? '编辑模型配置' : '添加模型配置'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={700}
        confirmLoading={loading}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="模型名称（唯一标识）"
            rules={[{ required: true, message: '请输入模型名称' }]}
          >
            <Input placeholder="例如：deepseek" disabled={!!editingModel} />
          </Form.Item>

          <Form.Item
            name="display_name"
            label="显示名称"
            rules={[{ required: true, message: '请输入显示名称' }]}
          >
            <Input placeholder="例如：DeepSeek V3" />
          </Form.Item>

          <Form.Item
            name="base_url"
            label="API 基础地址"
            rules={[{ required: true, message: '请输入 API 地址' }]}
          >
            <Input placeholder="例如：https://api.deepseek.com/v1" />
          </Form.Item>

          <Form.Item
            name="api_key"
            label="API Key"
            rules={[{ required: true, message: '请输入 API Key' }]}
          >
            <Input.Password placeholder="请输入 API Key" />
          </Form.Item>

          <Form.Item
            name="model_name"
            label="模型标识符"
            rules={[{ required: true, message: '请输入模型标识符' }]}
          >
            <Input placeholder="例如：deepseek-chat" />
          </Form.Item>

          <Form.Item
            name="max_tokens"
            label="最大 Token 数"
            initialValue={2000}
          >
            <InputNumber min={100} max={10000} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="temperature"
            label="温度参数"
            initialValue={0.7}
          >
            <InputNumber min={0} max={2} step={0.1} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="timeout"
            label="超时时间（毫秒）"
            initialValue={60000}
          >
            <InputNumber min={10000} max={300000} step={1000} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea rows={3} placeholder="模型描述信息（可选）" />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default AIModelPage;
